<template>
  <el-drawer
    title="视频库"
    :visible.sync="show"
    direction="rtl"
    :before-close="handleClose"
    :modal-append-to-body="false"
    size="50%"
  >
    <div class="drawer-container flex-v h-100">
      <div class="flex-b align-center drawer-header">
        <div class="flex align-center mao-radio-button-list">
          <mao-radio-button
            v-if="!onlyProduct"
            v-model="activeTab"
            value="视频库"
            label="视频库"
          />
          <mao-radio-button
            v-model="activeTab"
            value="视频素材"
            label="视频素材"
          />
        </div>
        <div class="border">
          <el-radio-group
            v-model="activeSort"
            size="mini"
            fill="#fff"
            text-color="#409EFF"
          >
            <el-radio-button value="全部" label="全部（616）" />
            <el-radio-button value="未使用" label="未使用（66）" />
            <el-radio-button value="已使用" label="已使用（0）" />
          </el-radio-group>
        </div>
      </div>
      <div v-if="activeTab === '视频库'" class="w-100">
        <div class="video-list-container">
          <div class="video-list scroll-box w-100">
            <el-popover
              v-for="(item, index) in categoryList"
              :key="item.id"
              placement="bottom"
              :title="item.categoryName"
              width="150"
              trigger="hover"
            >
              <div class="name">
                <div>状态：未使用</div>
                <div>视频数量:215</div>
              </div>
              <div slot="reference" class="video-item pointer">
                <dir-item
                  :item="item"
                  :index="index"
                  :checkable="true"
                  :editable="false"
                  only-name
                  @toggle="toggleDirCheck(index)"
                />
              </div>
            </el-popover>
          </div>
        </div>

        <div class="flex-e align-center footer">
          <el-button
            type="default"
            style="margin-right: 10px"
            @click="$emit('close')"
          >取消</el-button>
          <el-button type="primary" @click="submitCategory">确定</el-button>
        </div>
      </div>
      <div v-else class="w-100">
        <div class="video-list-container">
          <div class="video-list scroll-box w-100">
            <div
              v-for="(item, index) in videoList"
              :key="index"
              class="video-item rel"
            >
              <div class="abs w-100 flex-b align-center video-item-header" style="z-index: 11;">
                <mao-checkbox v-model="item.checked" />
                <!-- <div class="tag flex-c align-center">未使用</div> -->
              </div>
              <div class="poster" style="overflow: hidden">
                <MaoVideo :url="item.productUrl" :autoplay="false" />
              </div>

              <div class="name nowrap" style="margin-top: 5px">
                {{ item.productName }}
              </div>
            </div>
          </div>
        </div>

        <div class="flex-e align-center footer">
          <el-button
            type="default"
            style="margin-right: 10px"
            @click="$emit('close')"
          >取消</el-button>
          <el-button type="primary" @click="submitVideo">确定</el-button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import MaoVideo from '@/components/MaoVideo'
import MaoRadioButton from '@/components/MaoRadioButton'
import DirItem from '@/views/element/index/components/DirItem.vue'
import { getCategoryList, getList } from '@/api/product'

export default {
  components: { MaoVideo, DirItem, MaoRadioButton },
  props: {
    onlyProduct: {
      type: Boolean,
      default: false
    },
    show: {
      type: Boolean,
      default: false
    },
    active: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      activeTab: '视频库',
      activeSort: '全部',
      tabList: [{ name: '视频库' }, { name: '视频素材' }],
      videoList: [],
      categoryList: [
        {
          categoryName: '通用素材',
          id: '0',
          libraryName: '通用素材',
          checked: false
        }
      ],
      categoryPageMap: {
        pageNum: 1,
        total: 0,
        pageSize: 1
      },
      pageMap: {
        pageNum: 1,
        total: 0,
        pageSize: 10,
        current: 1
      }
    }
  },
  watch: {
    activeTab(val) {
      if (val === '视频库') {
        if (!this.categoryList.length) {
          this.initCategoryList()
        }
      } else {
        if (!this.videoList.length) {
          this.initVideoList()
        }
      }
    },
    active(val) {
      if (val === 0) {
        this.activeTab = '视频库'
      } else {
        this.activeTab = '视频素材'
      }
    }
  },
  created() {
    if (this.onlyProduct) {
      this.activeTab = '视频素材'
      this.initVideoList()
    } else {
      if (this.active === 0) {
        this.activeTab = '视频库'
        this.initCategoryList()
      } else {
        this.activeTab = '视频素材'
        this.initVideoList()
      }
    }
  },
  methods: {
    toggleDirCheck(index) {
      const item = this.categoryList[index]
      item.active = item.checked = !item.checked
      this.$set(this.categoryList, index, item)
    },
    submitVideo() {
      console.log('submitVideo:', this.videoList)
      const list = this.videoList
        .filter((item) => item.checked)
        .map((item) => item.id.toString())
      this.$emit('ok', {
        value: list.join(','),
        type: 'video',
        list: this.videoList.filter((item) => item.checked)
      })
    },
    async submitCategory() {
      const categoryIds = this.categoryList
        .filter((item) => item.checked)
        .map((item) => item.id.toString())
      const funcs = []
      for (let i = 0; i < categoryIds.length; i++) {
        const id = categoryIds[i]
        funcs.push(await this.initVideoListByCategory(id))
      }
      const resultList = []
      Promise.all(funcs).then((res) => {
        res.forEach((item) => {
          if (Array.isArray(item) && item.length) {
            resultList.push(...item)
          }
        })
        console.log('resultList', resultList)
        const value = resultList.map((item) => item.id).join(',')
        this.$emit('ok', {
          value: value,
          type: 'category',
          list: this.categoryList.filter((item) => item.checked)
        })
      })

      // 挨个调用库查视频接口
    },
    async getCategory(item) {
      console.log('getCategory', item)
      const list = await this.initVideoListByCategory(item.id.toString())
      this.$emit('ok', list.map((item) => item.id).join(','))
    },
    async initCategoryList(page = 1) {
      this.categoryPageMap.pageNum = page
      const res = await getCategoryList()
      if (res.success) {
        this.categoryList = [
          {
            categoryName: '通用素材',
            id: '0',
            libraryName: '通用素材',
            checked: false
          }
        ]
        const records = res.result.records.map((item) => {
          item.checked = false
          item.active = false
          return item
        })
        this.categoryList = [...this.categoryList, ...records]
      } else {
        this.$message.error(res.message)
      }
    },
    async initVideoListByCategory(productCategoryId = '') {
      return new Promise((resolve) => {
        if (productCategoryId) {
          getList({
            productCategoryId
          }).then((res) => {
            if (res.success) {
              const { records } = res.result
              resolve(records)
            } else {
              this.$message.error(res.message)
              resolve([])
            }
          })
        }
      })
    },
    async initVideoList() {
      return new Promise((resolve) => {
        getList({
          pageSize: 1000
        }).then((res) => {
          if (res.success) {
            const { current, total, records } = res.result
            this.pageMap.pageNum = current
            this.pageMap.total = total
            this.videoList = records.map((item) => {
              item.checked = false
              return item
            })
            resolve(records)
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    handleClose() {
      this.$emit('close')
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
    },
    changeTab(e) {
      console.log(e)
    }
  }
}
</script>
<style lang="scss" scoped>
.drawer-container {
  box-sizing: border-box;
  padding: 0 20px 20px;
  .drawer-header {
    margin-bottom: 40px;
  }
  .tag {
    font-size: 14px;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
    border-radius: 5px;
    background: rgba(56, 56, 56, 0.7);
    box-sizing: border-box;
    padding: 2px 8px;
  }
  .img {
    width: 90px;
    margin-bottom: 16px;
  }
  .name {
    font-size: 14px;
    font-weight: 400;
    color: rgba(0, 0, 0, 1);
  }
  .list {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-column-gap: 30px;
    grid-row-gap: 30px;
  }
  .footer {
    height: 50px;
    border-top: 1px solid #f2f3f4;
  }
  .video-list-container {
    height: calc(100vh - 200px);
  }
  .video-list {
    display: grid;
    grid-template-columns: repeat(5, calc(20% - 24px));
    grid-gap: 30px;
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    width: 100%;
  }
  .video-item-header {
    box-sizing: border-box;
    padding: 4px 6px;
  }
  .video-item {
    max-width: 148px;
    width: 100%;
    height: fit-content;
    .poster {
      width: 100%;
      max-width: 148px;
      height: 240px;
    }
  }
}
</style>
